//
//  ProductsViewController.swift
//  weile
//
//  Created by LKM on 16/10/9.
//  Copyright © 2016年 LKM. All rights reserved.
//

import UIKit

class ProductsViewController: BaseViewController ,UITableViewDelegate,UITableViewDataSource ,ProductsFilterParamViewBC ,ISearchAble{

    @IBOutlet weak var tableview: UITableView!
    var mListFooterLoadView :ListFooterLoadView!
    
    var refreshControl: UIRefreshControl!
    @IBOutlet weak var sv_filter: UIScrollView!
    @IBOutlet weak var sv_filter_height: NSLayoutConstraint!
    @IBOutlet weak var mProductsFilterParamView: ProductsFilterParamView!//过滤参数选择
    
    fileprivate var data:ProductsTo?;
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        mListFooterLoadView = ListFooterLoadView.createView();
        self.tableview.tableFooterView=mListFooterLoadView;
        
        self.tableview.register(UINib(nibName:"ProductsItem", bundle: nil), forCellReuseIdentifier: "ProductsItem")
    
        //tableview参数设置
        tableview.rowHeight = 120.7//10+100+10+0.7
        tableview.separatorStyle = .none
        tableview.contentInset = UIEdgeInsetsMake(0,0,40+30+28 + 30,0)//UIEdgeInsetsMake(0, 0, MainTabBarHeight, 0)
        tableview.scrollIndicatorInsets = tableview.contentInset
        tableview.delegate=self;
        tableview.dataSource = self;
        //tableview参数设置  end
        
        
        // 添加刷新控件
        refreshControl = UIRefreshControl()
//        refreshControl.attributedTitle = NSAttributedString(string: "松开后自动刷新")
        tableview.addSubview(refreshControl)
        refreshControl.addTarget(self, action: #selector(loadData(_:)), for: .valueChanged)
        // 添加刷新控件 end
        
       
        
       //ViewHelp.setOnClickListening(mProductsFilterParamView, self, #selector(onClickCloseProductsFilterParamView) )
        mProductsFilterParamView.delegate=self
        
    }
    override func viewWillAppear(_ animated: Bool) {
        if(data == nil){
            loadData(false)
        }
        
    }
    var isOnlyShowList : Bool = true{
        didSet{
            if(self.isOnlyShowList){
                if(  self.sv_filter_height.constant != 0 ){
                    self.sv_filter_height.setTag(&R.id.tag_height, self.sv_filter_height.constant)
                }
            }
            
            self.sv_filter_height.constant = self.isOnlyShowList ? 0 : max( self.sv_filter_height.constant , self.sv_filter_height.getTag(&R.id.tag_height) as! CGFloat  )
        }
    }
    
    var mainId:String=""
    //会导致 集装箱（home的第二个item）FilterBar没显示数据
//        {
    
//        didSet{
//            
//            LKMLog("=====\(self.title ) \(isViewLoaded)")
//            
//            if loadData(false){
//                refreshControl.beginRefreshing()
//            }
//        }
//    };
    var keyWord:String="";
    
    func searchForKeyWord(keyWord: String, isForceRefresh: Bool) {
        if(self.keyWord != keyWord){
            self.keyWord = keyWord;
            forceRefresh()
        }else if isForceRefresh{
            forceRefresh()
        }
    }
    
    var paramFilterIds:String="";
    
    
    var listData: [ProductItemM] = Array();//
    var curPage = 1;//第一开始
    var isLoadIng = false;//是否加载中
    var isLoadAppending = false;//是否加载更多数据
    var hasMoreData=true;//是否有更多数据
    
    @discardableResult
    func loadData(_ isLoadAppend :Bool) -> Bool{
        if isLoadIng {
            return isLoadAppend == isLoadAppending;
        }
        self.isLoadAppending=isLoadAppend;
        isLoadIng=true
        
        if(isLoadAppend){
            mListFooterLoadView.setAppending()
        }else{
            ViewHelp.showProgressActivityDelay(containView: self.view)
            mListFooterLoadView.setRefreing()
        }
        
        let taskSerialNumber=Api.getProductls(preTaskSerialNumber: nil,page: isLoadAppend ? (curPage + 1) : 1, mainId: self.mainId ,filterIds: paramFilterIds,keywords: keyWord){ (re:ResponEntity) in
            self.isLoadIng=false;
            if(re.isSuccess()){
                let oldData=self.data;
                self.data = re.data as? ProductsTo;
                
                //数据解析为为空
                if(self.data==nil){
                    return//但是这是不可能的
                }
                
                //保存选择的
                if(oldData != nil){
                    if(oldData?.filters != nil){
                        self.data?.filters=oldData?.filters;
                    }
                }else{
                    if(self.data?.filters != nil){
                        for f1 in (self.data?.filters)! {
//                            if f1 == nil {
//                                continue;
//                            }
                            if(f1.filter == nil){
                                f1.filter = [ProductsToFilter2]()
                            }
                            let f2 = ProductsToFilter2();
                            f2.name = "全部"
                            f2.id="";
                            f1.filter?.insert(f2, at: 0);
                            
                        }
                        
                        //第一次加载数据
                        self.binFilterBar(self.data!.filters);
                        
                    }
                    
                }
                
                //数据是那些----
                let hasListData = !(CollectionHelp.isEmpty( self.data?.prolist )) //这次加载的有数据没//!(self.data?.prolist == nil);
                if(self.isLoadAppending){
                    self.curPage += hasListData ? 1 : 0;
                }else{
                    self.listData.removeAll();
                    self.curPage = 1;
                }
                self.listData += self.data?.prolist ?? Array();
                
                self.hasMoreData = hasListData
                //没有更多数据了
                self.mListFooterLoadView.setNone(hasNextPage: hasListData)
                //数据是那些----end
                
                self.tableview.reloadData()
            }else{
                ViewHelp.showTipsView(containView: self.view, tips: re.msg);
            }
            self.refreshControl.endRefreshing()
            ViewHelp.hideProgressActivity(containView: self.view)
        }
        curLoadTaskSerialNumber=taskSerialNumber;
        taskAlls.append(taskSerialNumber);
        
        return true;
    }
    func forceRefresh(){
        isLoadIng=false;
        if let ts = curLoadTaskSerialNumber{
            Api.destroyTask(taskSerialNumbers: [ts])
        }
        
        loadData(false);
    }
    
    var curLoadTaskSerialNumber:Int?;
    var taskAlls = [Int]();
    deinit {
        //界面退出肯定就不登陆咯
        Api.destroyTask(taskSerialNumbers: taskAlls);
    }

    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    //---------mProductsFilterParamView------
    var mProductFilterItemViews:[ProductFilterItemView]=[ProductFilterItemView]()
    func binFilterBar(_ filters: [ProductsToFilter1]?){
        if filters == nil {
            return
        }
        ViewHelp.removeAllSubView(self.sv_filter)
        mProductFilterItemViews.removeAll()
        
        let count = filters?.count ?? 0;
        
        let itemw=CGFloat( Double(sv_filter.width)/min(3.5, Double(count)) );
//        itemw += 100;
        self.sv_filter.contentSize.width = (itemw) * CGFloat(count)
        for i in 0 ..< count{
            let f = filters?[i];
            
            let fi=ProductFilterItemView.createView()
            mProductFilterItemViews.append(fi);
            fi.x = CGFloat(i*Int(itemw));
            ViewHelp.setViewWidthHeigth(fi, itemw, self.sv_filter.height)
            fi.binData((f?.name)!, tag: i);
            ViewHelp.setOnClickListening(fi, self, #selector(onProductFilterItemViewClick(_:)) )
            self.sv_filter.addSubview(fi)
        }
    }
    
    //点击第一
    var curProductFilterItemView:ProductFilterItemView?;
    func onProductFilterItemViewClick(_ rg:UITapGestureRecognizer ){
//        mProductFilterItemViews[fi.getTag() as! Int]
       
        
        let fi = rg.view as! ProductFilterItemView;
        curProductFilterItemView = fi;
        
        let iss=fi.isSelect()
        
        for f in mProductFilterItemViews{
            f.setSelect(false);
        }
        
        fi.setSelect(!iss);
        
        //都没选中，隐藏
        if !fi.isSelect() {
            mProductsFilterParamView.close();
            mProductsFilterParamView.binData(filter2s: [ProductsToFilter2]())
        }else{
            mProductsFilterParamView.show();
            mProductsFilterParamView.binData(filter2s: data?.filters?[ fi.getTag() as! Int ].filter ?? [ProductsToFilter2]() )
        }
    }
    //点击第2
    func onClickItem(_ v: ProductsFilterParamView, _ data: ProductsToFilter2, _ index: Int) {
        if data.isSelect{
            paramFilterIds="";
            for f1 in self.data?.filters ?? [ProductsToFilter1]() {
                for f2 in f1.filter ?? [ProductsToFilter2](){
                   
                    if( f2.isSelect ){
                        if(!paramFilterIds.isEmpty){
                            paramFilterIds += ","
                        }
                        paramFilterIds += f2.id ?? "";
                    }
                    
                    
                }//for
            
            }// for
            
            forceRefresh()
            
            //不会点击就取消  所以在isSelect中
            curProductFilterItemView?.binData(data.name!, tag: curProductFilterItemView?.getTag())
        }
        
        onClickCloseProductsFilterParamView();
        
    }
    
    func onClickCloseProductsFilterParamView(){
        mProductsFilterParamView.close();
        for f in mProductFilterItemViews{
            f.setSelect(false);
        }

    }
    //---------mProductsFilterParamView--end----
    
    
    // MARK: - UITableViewDataSource
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let homeCell = tableView.dequeueReusableCell(withIdentifier: "ProductsItem") as! ProductsItem
        homeCell.selectionStyle = .none
        homeCell.mProductItemM = self.listData[(indexPath as NSIndexPath).row]
        
        let count:Int=self.tableView( tableView, numberOfRowsInSection:1);
        if(indexPath.row+1>=count){
            //加载更多数据
            if hasMoreData{
                //一般到显示倒数第二个就会去加载
                loadData(true);
            }
            
        }

        
        return homeCell
    }
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let mProductItemM = self.listData[(indexPath as NSIndexPath).row]
        ActivityRequest.goProductDetailController(navigationController!,mProductItemM.id!);
    }
    
    
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

